<template>
  <div>
    <div v-if="placeholder" style="font-size: 0.9rem;margin: 2px">{{ placeholder }}</div>
    <van-uploader
      v-model="fileList"
      multiple
      :after-read="doUpload"
      :before-delete="deleteFile"
      @click-preview="viewFile"
      :accept="uploadAccept">
    </van-uploader>
  </div>
</template>

<script>
  import { postAction,getFileAccessHttpUrl } from '@/api'
  import { downloadAbled } from '@/util/util'

  export default {
    name: 'ChatUploader',
    props:{
      biz:{
        type:String,
        default:'app',
        required:false
      },
      value:{
        type:String,
        required:false
      },
      placeholder:{
        type:String,
        required:false,
        default:''
      },
      type:{
          type:String,
          required:true
      }

    },
    watch:{
      value:{
        immediate:true,
        handler(val){
          this.initFileList(val)
        }
      }
    },
    model: {
      prop: 'value',
      event: 'input'
    },
    computed:{
      uploadAccept(){
        if(this.type==='image'){
			console.log('支持上传图片')
            return 'image/*'
        }else{
			console.log('支持上传所有类型文件')
            return '*'
        }
      }
    },
    data(){
      return {
        // {url:''} {content:'base64',file:'file对象'}
        fileList:[],
        uploadUrl:window._CONFIG['domainURL']+"/sys/common/upload",
        innerList:[]
      }
    },
    methods:{
      getNewPath(path){
        if(!path){
          path = ''
        }
        if(!this.value){
          return path
        }else{
          return this.value+","+path
        }
      },
      addInnerObj(file,url){
        this.innerList.push({
          fileName:file.name,
          filePath:url,
          fileSize:file.size
        })
      },
      deleteInnerObj(url){
        this.innerList = this.innerList.filter(item=>{
          return url!=item.filePath
        })
      },
      doUpload(obj){
		const files = Array.isArray(obj) ? obj : [obj];
		// 检查文件类型是否支持
		const hasInvalidFile = files.some(fileObj => {
			// 当上传类型为image时，检查文件MIME类型是否以image/开头
			if (this.type === 'image' && !fileObj.file.type.startsWith('image/')) {
				return true; // 发现不支持的类型
			}
			return false;
		});

		// 如果存在不支持的文件类型
		if (hasInvalidFile) {
			this.$toast('文件类型不支持');
			// 从fileList中移除这些文件
			this.fileList = this.fileList.filter(item => 
				!files.some(f => f.file === item.file)
			);
			return;
		}
		
		files.forEach(fileObj => {
			let formData = new FormData();
			formData.append("file",fileObj.file,fileObj.file.name)
			formData.append("bizPath",this.biz)
			postAction(this.uploadUrl,formData).then(res=>{
				console.log("res",res);
				if(res.success){
					this.addInnerObj(fileObj.file,res.message)
					const inputValue = this.$route.path.includes('coordination/chat/') ? `${this.getNewPath(res.message)},${fileObj.file.size}` : this.getNewPath(res.message) 
					this.$emit('input',this.getNewPath(inputValue))
				}else{
					this.$toast('文件上传失败,请联系管理员')
					this.fileList.pop()
				}
			})
		})
      },
      notImg(path){
        let arr = ['txt','doc','pdf','docx','ppt','pptx','xls','xlsx']
        let r = false
        for(let a of arr){
          if(path.endsWith(a)){
            r = true
            break;
          }
        }
        return r;
      },
      deleteFile(obj){
        console.log("obj",obj)
        console.log("this.value",this.value)
        let arr = this.value.split(",")
        let newPath = arr.filter(item=>{
          let a = obj.url.indexOf(item)<0 && item.indexOf(obj.url)<0
          if(!a){
            this.deleteInnerObj(item)
          }
          return a;
        }).join(",")
        this.$emit('input',newPath)
        return true
      },
      initFileList(paths){
        if(!paths || paths.length==0){
          this.fileList = [];
          this.innerList = []
          return;
        }
        let fileList=[]
        let arr = paths.split(",")
        for(var a=0;a<arr.length;a++){
          if(this.notImg(arr[a])){
            fileList.push({
              type:'file',
              url:arr[a].substring(arr[a].lastIndexOf("/")+1)
            })
          }else{
            fileList.push({
              url:getFileAccessHttpUrl(arr[a])
            })
          }

        }
        this.fileList = [...fileList]
      },

      getNeedJsonStr(){
        return JSON.stringify(this.innerList)
      },
      viewFile(obj){
        if(obj.type==='file'){
          let url = getFileAccessHttpUrl(obj.url);
          downloadAbled(url).then(()=>{
            location.href = url;
          }).catch(()=>{
            this.$toast('文件识别失败!')
          })
        }
        return true;
      }
    }
  }
</script>

<style scoped>

</style>